import React, { useEffect, useMemo, useState } from 'react'
import { Layout } from '../components/Layout'
import { DataTable, Column } from '../components/DataTable'
import { EmptyState, ErrorState } from '../components/States'

type LogSummary = {
  id: number
  server_id: number
  started_at: string
  ended_at: string
  bytes_count: number
}

type LogDetail = LogSummary & { content: string }

type ServerRead = {
  id: number
  name: string
}

async function api<T>(input: RequestInfo, init?: RequestInit): Promise<T> {
  const resp = await fetch(input, {
    ...init,
    headers: { 'Content-Type': 'application/json', ...(init?.headers || {}) },
  })
  if (!resp.ok) throw new Error(await resp.text())
  return resp.json()
}

export function LogsPage(): JSX.Element {
  const [logs, setLogs] = useState<LogSummary[]>([])
  const [servers, setServers] = useState<ServerRead[]>([])
  const [serverId, setServerId] = useState<number | 'all'>('all')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const serverIdToName = useMemo(() => new Map(servers.map(s => [s.id, s.name])), [servers])

  const loadServers = async () => {
    try {
      const list = await api<ServerRead[]>('/api/servers/')
      setServers(list.map(s => ({ id: s.id, name: s.name })))
    } catch {}
  }

  const loadLogs = async (sid: number | 'all') => {
    setLoading(true)
    setError(null)
    try {
      const q = sid === 'all' ? '' : `?server_id=${sid}`
      const data = await api<LogSummary[]>(`/api/logs/${q}`)
      setLogs(data)
    } catch (e: any) {
      setError(e.message)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    loadServers()
  }, [])

  useEffect(() => {
    loadLogs(serverId)
  }, [serverId])

  const rows = useMemo(() => logs.map(l => ({
    ...l,
    serverName: serverIdToName.get(l.server_id) || `#${l.server_id}`,
  })), [logs, serverIdToName]) as Array<LogSummary & { serverName: string }>

  const download = async (logId: number) => {
    try {
      const detail = await api<LogDetail>(`/api/logs/${logId}`)
      const name = serverIdToName.get(detail.server_id) || `server-${detail.server_id}`
      const started = new Date(detail.started_at).toISOString().replace(/[:.]/g, '-')
      const filename = `log-${name}-${started}.txt`
      const blob = new Blob([detail.content || ''], { type: 'text/plain;charset=utf-8' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = filename
      document.body.appendChild(a)
      a.click()
      a.remove()
      URL.revokeObjectURL(url)
    } catch (e) {
      console.error(e)
      alert('下载失败')
    }
  }

  return (
    <Layout>
      <div className="container">
        <div className="panel">
          <div className="header">
            <h3 className="title">会话日志</h3>
            <div className="toolbar">
              <select className="select" value={serverId}
                onChange={e => setServerId(e.target.value === 'all' ? 'all' : Number(e.target.value))}
              >
                <option value="all">全部服务器</option>
                {servers.map(s => (
                  <option key={s.id} value={s.id}>{s.name}</option>
                ))}
              </select>
              {loading && <span className="muted">加载中...</span>}
              {error && <span style={{ color: 'salmon' }}>{error}</span>}
            </div>
          </div>
          <div className="content">
            {error && <ErrorState message={error} onRetry={() => loadLogs(serverId)} />}
            {!error && rows.length === 0 ? (
              <EmptyState title="暂无日志" description="连接服务器进行会话后，将在此显示历史记录" />
            ) : (
              <DataTable
                data={rows}
                searchableKeys={["serverName", "id"] as any}
                columns={[
                  { key: 'id', title: 'ID', sortable: true, render: r => <span className="mono">#{r.id}</span> },
                  { key: 'serverName' as any, title: '服务器', sortable: true },
                  { key: 'started_at', title: '开始', sortable: true, render: r => new Date(r.started_at).toLocaleString() },
                  { key: 'ended_at', title: '结束', sortable: true, render: r => new Date(r.ended_at).toLocaleString() },
                  { key: 'bytes_count', title: 'Bytes', sortable: true },
                  { key: 'id', title: '操作', render: r => (
                    <div style={{ display: 'flex', gap: 8 }}>
                      <button className="btn btn-sm" onClick={() => download(r.id)}>下载</button>
                    </div>
                  )},
                ] as Column<(typeof rows)[number]>[]}
              />
            )}
          </div>
        </div>
      </div>
    </Layout>
  )
}

